package json;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.util.JDKUtils;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 利用Hutool的工具类来把json数据形式转换成java对象
 *  JSONUtil里toJsonStr(Obj)可以把对象转换为json格式
 *  toBean(Json,Obj.class)可以把Json格式的数据转换为指定的Obj对象
 *  toJSONPrettyStr()将java对象转换成格式化良好的JSON
 *  parseArray,toList():将json串转换成java中的集合
 *
 */
public class jsonTest01 {
    @Test
    public void ObjectTOJson(){
        Student student = new Student(20021031, "无极", "男", 25);
        String jsonStudent = JSONUtil.toJsonStr(student);
        System.out.println(jsonStudent);
    }

    @Test
    public void JsonTOObject(){
        String jsonStudent= "{\"sno\":20021031,\"name\":\"无极\",\"gender\":\"男\",\"age\":25}";
        Student student = JSONUtil.toBean(jsonStudent,Student.class);
        System.out.println(student);
    }

    @Test
    public void ListToJson(){
        List<Student> students = Arrays.asList(
                new Student(20021031, "无极", "男", 25),
                new Student(20020603, "蓝莓", "鹦鹉", 30)

        );
        System.out.println(JSONUtil.toJsonStr(students));
        System.out.println(JSONUtil.toJsonPrettyStr(students));
    }

    @Test
    public void JsonToList(){
        String JsonStr ="[{\"sno\":20021031,\"name\":\"无极\",\"gender\":\"男\",\"age\":25},{\"sno\":20020603,\"name\":\"蓝莓\",\"gender\":\"鹦鹉\",\"age\":30}]";
        JSONUtil.parseArray(JsonStr).toList(Student.class).forEach(System.out::println);
    }

    @Test
    public void MapToJson(){
        List<Student> students = Arrays.asList(
                new Student(20021031, "无极", "男", 25),
                new Student(20020603, "蓝莓", "鹦鹉", 30)

        );
        Map<String, Student> map = students.stream().collect(Collectors.toMap(student -> student.getName(), student -> student));
        System.out.println(JSONUtil.toJsonStr(map));
        System.out.println(JSONUtil.toJsonPrettyStr(map));
    }
}
